package baseFx.springboot;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

public class FxRequestListener implements ServletRequestListener {
    private final static String key = UUID.randomUUID().toString();
    private MvcEvents mvcEvents;

    public FxRequestListener(MvcEvents mvcEvents) {
        this.mvcEvents = mvcEvents;
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        if (request.getRequestURI().endsWith("favicon.ico")) {
            return;
        }
        RequestEventArgs args = new RequestEventArgs(request);
        args.request.setAttribute(key, args);
        mvcEvents.onReuqestBefore(args);
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        Object value = sre.getServletRequest().getAttribute(key);
        if (value != null) {
            RequestEventArgs args = (RequestEventArgs) value;
            mvcEvents.onReuqestAfter(args);
        }
    }
}
